define(function(require){
    var main = require('/static/main.js');
    var m = new main();
    var level = {
        isActive : false,
        activeindex :0,
        levelList : [],
        actionList : [],
        table : '',
        init:function(){
            m.loadmenu('.cate-jurisdiction',0);
            this.bindEvent();
            this.getList();
        },
        getList:function(){
            //获取管理员列表
            level.table = $("#datatable").dataTable({
                ajax: function (data, callback, settings){
                    //ajax请求数据
                    $.ajax({
                        type: "POST",
                        url: "/jurisdiction/get-level-list",
                        dataType: "json",
                        success: function (result){
                            var returnData = {};
                            returnData.draw = data.draw;
                            returnData.total = result.total;
                            returnData.data = result.data;
                            level.levelList = result.data;
                            callback(returnData);
                        }
                    });
                },
                'bPaginate': true,
                "bDestory": true,
                "bRetrieve": true,
                "bFilter":false,
                "bSort": false,
                "bProcessing": true,
                "autoWidth": false,
                "searching":false,
                "aoColumns": [
                    {"mDataProp": "LevelName"},
                    {"mDataProp": "MytipLevelId",
                        "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            $(nTd).html('<div class="option_btn"><span class=" EditLevel" data-toggle="modal" data-target="#EditLevel">编辑</span>\
                               <span class="btn-setting">设置</span>');

                        }
                    },
                ],
                "fnCreatedRow": function (nRow, aData, iDataIndex) {
                },
                "fnInitComplete": function (oSettings, json) {
                }
            });
        },
        bindEvent:function(){
            //编辑
            $(document).on('click','.EditLevel',function(){
                var index = $(this).closest("tr").index();
                level.activeindex = index;
                var data = level.levelList[index];
                $("#EditLevel .LevelName").val(data.LevelName);
                level.showmessage($("#EditLevel .error"),false);
            });
            //编辑提交
            $(document).on('click','#EditLevel .btn-sure',function(){
                var data = level.levelList[level.activeindex];
                var JsonData ={
                    MytipLevelId : data.MytipLevelId,
                    LevelName : $("#EditLevel .LevelName").val().trim(),
                }
                if(JsonData.LevelName.length < 1){
                    level.showmessage($("#EditLevel .error"),true,'请输入管理员名称');
                    return false;
                }
                level.showmessage($("#EditLevel .error"),false);
                level.resetFrom($("#EditLevel"));
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: '/jurisdiction/mytip-level-update',
                    data:JsonData,
                    success: function (ret) {
                        $("#EditLevel").modal('hide');
                        level.resetFrom($("#EditLevel"));
                        if(ret.IsBizSuccess){
                            var table = $('#datatable').DataTable();
                            table.ajax.reload();
                            layer.msg('修改成功！');
                        }else{
                            layer.msg('修改失败！');
                        }
                    }
                });
            });

            //设置
            var Settingaction = false;
            $(document).on('click','#datatable .btn-setting',function(){
                if(Settingaction){
                    return false;
                }
                $("#RoleUpdate").show();
                var index = $(this).closest("tr").index();
                level.activeindex = index;
                var data = level.levelList[index];
                var MytipLevelId = data.MytipLevelId;
                level.MytipLevelId = MytipLevelId;
                var JsonData = {MytipLevelId:MytipLevelId};
                if( (typeof(level.actionList[MytipLevelId]) != "undefined")){
                    $('#jstree'+MytipLevelId).addClass("show").siblings().removeClass("show");
                    return false;
                }
                Settingaction = true;
                    $.ajax({
                    type: "post",
                    dataType: "json",
                    url: '/jurisdiction/level-action-get-list',
                    data:JsonData,
                    success: function (ret) {
                        Settingaction = false;
                        if(ret.IsBizSuccess){
                            var str = ' <div id="jstree'+MytipLevelId+'" data-roleid="'+MytipLevelId+'" style="display:none"><ul>';
                            $.each(ret.Models,function(key,val){
                                if((typeof(val.ActionList) != "undefined") && (val.ActionList.length > 0)){
                                    var successlength = 0;
                                    var childsStr = '';
                                    $.each(val.ActionList,function(ke,va){
                                        if(va.IsCheck  == true){
                                            successlength ++ ;
                                            childsStr += '<li data-jstree=\'{"type":"input","selected":"true"}\' data-actionid="'+va.ActionId+'">'+va.ActionName+'</li>';
                                        }else{
                                            childsStr += '<li data-jstree=\'{"type":"input"}\' data-actionid="'+va.ActionId+'">'+va.ActionName+'</li>';
                                        }
                                    });
                                    if(val.ActionList.length == successlength){
                                        str += '<li class="jstree-open" data-jstree=\'{"selected":"true"}\' data-cid="'+val.ControllerId+'" >'+val.ControllerName+"<ul class='jstree-first-children' >"+childsStr;
                                    }else{
                                        str += '<li class="jstree-open" data-cid="'+val.ControllerId+'">'+val.ControllerName+"<ul class='jstree-first-children'>"+childsStr;
                                    }

                                    str += '</ul>';
                                }else{
                                    //str += '<li class="jstree-open customtree" data-jstree=\'{"type":"input"}\'>'+val.Name;
                                }
                                str+='</li>';
                            });
                            str += '</ul></div>';
                            level.actionList[MytipLevelId] =  MytipLevelId;
                            $("#RoleMenuList").append(str);
                            $('#jstree'+MytipLevelId).addClass("show").siblings().removeClass("show");
                            level.jsTree( $('#jstree'+MytipLevelId));
                            $("#RoleUpdate").show();
                        }else{
                        }
                    }
                });

            });
            var Relationaction = false;
            //保存关联信息
            $(document).on('click','#RoleUpdate',function(){
                if(Relationaction){
                    return false;
                }
                var obj = $("#RoleMenuList").find(".show");
                if(obj.length > 0){
                    var actionList = new Array();
                    obj.find('.jstree-open').each(function(k,v){
                        var cid = $(this).data("cid");
                        $(this).find(".jstree-children li").each(function(key,val){
                            if($(this).attr('aria-selected') == 'true'){
                                var data = {ControllerId:cid,ActionId:$(this).data("actionid")};
                                actionList.push(data);
                            }
                        });
                    });
                    var JsonData = {MytipLevelId: level.MytipLevelId,Data:actionList};
                    Relationaction = true;
                    $.ajax({
                        type: "post",
                        dataType: "json",
                        url: '/jurisdiction/level-action-save',
                        data: JsonData,
                        success: function (ret) {
                            Relationaction = false;
                            if(ret.IsBizSuccess){
                                layer.msg('操作成功！');
                            }else{
                                layer.msg('操作失败！');
                            }
                        }
                    });
                }else{
                    layer.msg('请选择等级！');
                }

            });


        },
        jsTree:function(obj){
            obj.jstree({
                "core" : {
                    "multiple" : true, // 允许多选
                    'animation' : false
                },
                'expand_selected_onload' : false, //选中项蓝色底显示
                //"plugins": ["types", ],
                'plugins' : ["types","dnd",'checkbox', 'search'],  //如果使用checkbox效率会降低, 'wholerow'会把线隐藏掉
                "types": {
                    "default": {
                        "icon": "fa fa-folder"
                    },
                    "input": {
                        "icon": "fa fa-square-o"
                    }
                }
            }).bind('click.jstree', function(event) {

            });
        },
        showmessage:function(_obj,isshow,str){
            if(isshow){
                _obj.html(str).show();
            }else{
                _obj.html('').hide();
            }
        },
        //重置表单
        resetFrom:  function (_obj){
            _obj.find("form").each(function (index) {
                _obj.find("form")[index].reset();
            });
            level.showmessage(_obj.find(".error"),false);
        }
    }
    level.init();
});
